﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.CardAcct.Interfaces;
using PARK.CardAcct.Entitys.Dto.BaseEmployeeLog;
using PARK.CardAcct.Entitys;
using PARK.System.Entitys.Model.Permission.User;

namespace PARK.CardAcct.BaseEmployeeLog
{
    /// <summary>
    /// 卡户日志服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Card", Name = "EmployeeLog", Order = 200)]
    [Route("api/card/[controller]")]
    public class EmployeeLogService : IEmployeeLogService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<EmployeeLogEntity> _baseEmployeeLogRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="EmployeeLogService"/>类型的新实例
        /// </summary>
        public EmployeeLogService(
            ISqlSugarRepository<EmployeeLogEntity> baseEmployeeLogRepository,
            IUserManager userManager)
        {
            _baseEmployeeLogRepository = baseEmployeeLogRepository;
            _db = _baseEmployeeLogRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取卡户日志
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<EmployeeLogEntity>().FirstAsync(p => p.LogId == id);
            var output = entity.Adapt<EmployeeLogInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取卡户日志列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] EmployeeLogListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "logId" : input.sidx;
                //选中公司查询全部
                if (input.departId == userInfo.companyId)
                {
                    input.departId = null;
                }
                //日志日期
                List<string> querydate = input.createDate != null ? input.createDate.Split(',').ToObeject<List<string>>() : null;
                DateTime? startate = querydate != null ? Ext.GetDateTime(querydate.First()) : null;
                DateTime? enddate = querydate != null ? Ext.GetDateTime(querydate.Last()) : null;
                var data = await _db.Queryable<EmployeeLogEntity>()
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.JobNo.Contains(input.keyword) || p.ReallName.Contains(input.keyword) || p.CardNo.Contains(input.keyword) || p.NewCardNo.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.logKind), p => p.LogKind.Equals(input.logKind))
                     .WhereIF(!string.IsNullOrEmpty(input.departId), p => p.DepartId.Equals(input.departId))
                    //日志日期
                    .WhereIF(querydate != null, u => u.CreateDate >= new DateTime(startate.ToDate().Year, startate.ToDate().Month, startate.ToDate().Day, 0, 0, 0))
                    .WhereIF(querydate != null, u => u.CreateDate <= new DateTime(enddate.ToDate().Year, enddate.ToDate().Month, enddate.ToDate().Day, 23, 59, 59))
                    .Select(it => new EmployeeLogListOutput
                    {
                        logId = it.LogId,
                        jobNo = it.JobNo,
                        reallName = it.ReallName,
                        departName = it.DepartName,
                        cardNo = it.CardNo,
                        newCardNo = it.NewCardNo,
                        logKind = it.LogKind,
                        logKindName = it.LogKindName,
                        summary = it.Summary,
                        createDate = it.CreateDate,
                        createUserName = it.CreateUserName,
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<EmployeeLogListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 删除卡户日志
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<EmployeeLogEntity>().FirstAsync(p => p.LogId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                var isOk = await _db.Deleteable<EmployeeLogEntity>().Where(d => d.LogId == id).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
    }
}
